package org.ytor.core.sysapi.login.api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.*;
import org.ytor.common.enums.RespCode;
import org.ytor.common.exception.BaseException;
import org.ytor.common.model.R;
import org.ytor.common.util.cache.C;
import org.ytor.core.model.LoginUser;
import org.ytor.core.sysapi.login.loginc.LoginLogic;
import org.ytor.core.sysapi.login.req.LoginReq;
import org.ytor.core.sysapi.user.resp.SysUserDetailResp;


@RestController
@RequestMapping("/sys")
@RequiredArgsConstructor
@Tag(name = "登录相关")
public class LoginController {

    private final LoginLogic loginService;

    /**
     * 执行登录
     */
    @PostMapping("/doLogin")
    @Operation(summary = "执行登录", description = "执行登录")
    public R<SysUserDetailResp> doLogin(@Valid @RequestBody LoginReq loginReq) {
        return R.success("登陆成功", loginService.doLogin(loginReq));
    }

    /**
     * 执行登出
     */
    @GetMapping("/logout")
    @Operation(summary = "执行登出", description = "根据token执行登出")
    public R<?> logout(@CookieValue(value = "Authorization", required = false) String token, HttpServletResponse resp) {
        //移除缓存
        C.remove(token);

        //移除前端cookie
        ResponseCookie cookie = ResponseCookie.from("Authorization", token)
                .path("/")
                .httpOnly(false)
                .maxAge(0)
                .build();
        resp.addHeader("Set-Cookie", cookie.toString());

        return R.success("退出成功");
    }

    /**
     * 获取登录验证码
     */
    @GetMapping("/getCode")
    @Operation(summary = "获取登录Code", description = "code可能是图形码，可能是短信，可能是邮寄，根据业务而定")
    public R<?> getCaptcha() {
        return R.success();
    }

    /**
     * 根据token获取用户详情数据
     */
    @GetMapping("/queryDetailByToken")
    @Operation(summary = "获取用户详情数据", description = "根据token获取用户详情数据")
    public R<SysUserDetailResp> queryDetailByToken(@CookieValue(value = "Authorization", required = false) String token) {
        if (token == null) {
            throw new BaseException(RespCode.NOT_LOGIN);
        }
        LoginUser loginUser = C.get(token);
        if (loginUser == null) {
            //虽然根据token没有查到数据，但带有token，还是认为用户之前登录过，只是过期了
            throw new BaseException(RespCode.LOGIN_TIMEOUT);
        }

        return R.success(loginService.queryUserDetail(loginUser.getId()));
    }

}
